package exrefelect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Field 的使用
 * @author: knowno
 * @create: 2025-09-17 14:26
 * @Version 1.0
 **/
public class TestField {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException {

        //得到一个Person类的Class对象
        Class cls = Person.class;
        //获取字段
        //1 获取字段 ->getFields ->只能获取public的字段
        System.out.println("************getFields**********");
        Field[] fields = cls.getFields();

        Object o = cls.newInstance();

        for (Field field : fields) {
            System.out.println(field+" "+field.getModifiers());
            //给age字段赋值
            field.set(o,18);
            //获取age字段的值
            System.out.println(field.get(o));
        }
        //2 获取所有的字段 ->getDeclaredFields->可以获取所有的字段,包括私有的
        System.out.println("************getDeclaredFields**********");
        Field[] declaredFields = cls.getDeclaredFields();

        for (Field field : declaredFields) {
            System.out.println(field+" "+field.getModifiers());
            if (field.getModifiers()==2) {
                //私有的字段,需要设置Accessible为true
                field.setAccessible(true);
                //给名字赋值
                field.set(o, "knowno");
                //获取名字的值
                System.out.println(field.get(o));
            }
        }

    }
}
